package com.hzit.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.common.R;
import com.hzit.gateway.properties.AuthProperties;
import com.hzit.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.Cookies;

import java.util.Arrays;
import java.util.List;

/**
 * 功能：定义全局过滤器进行jwt签权处理
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private AuthProperties properties;
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

		ServerHttpRequest request = exchange.getRequest();
		ServerHttpResponse response = exchange.getResponse();
		//1. 从配置文件中获取白名单列表
		List<String> whiteList = properties.getWhites();
		//1. 判断当前的请求路径是否在白名单中
		String path = request.getURI().getPath();
		if(whiteList.contains(path)){
			return chain.filter(exchange);
		}

		//4. 得到前端传入的请求头信息
		List<String> authorization = request.getHeaders().get("Authorization");
		String s = authorization.get(0);
		String jwt_token = s.substring(7);      // 值以Bearer 开头
		//5. 解析出jwt_token中的key=token这个值
		Claims claims = JwtUtils.parseToken(jwt_token);
		String uuid = claims.get("token").toString();

		String key = "login-token:" + uuid;
		if(redisTemplate.hasKey(key)){
			return chain.filter(exchange);
		}

		//3.2 验证不通过
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
		String msg = "用户不合法！";
		// response.addCookie(new Cookie("token","ferfsfvs432423fsfsdafsdsfsdfs"));
		// let token = Cookies.get("token")

		R result = R.error(HttpStatus.UNAUTHORIZED.value(),msg);  //HttpStatus.UNAUTHORIZED.value() == 401
		DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());

		return response.writeWith(Mono.just(dataBuffer));
	}

	@Override
	public int getOrder() {
		return -100;
	}

}
